/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package cn.laike.modules.dev.utils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import cn.laike.common.utils.RedisUtils;
import cn.laike.common.utils.mp.MpUtils;
import cn.laike.modules.wechat.entity.WechatEntity;
import cn.laike.modules.wechat.service.WechatService;
import net.sf.json.JSONObject;

/**
 * 接口配置工具类
 * 
 * @author Administrator
 *
 */
@Service
public class MpCacheUtils implements ApplicationContextAware {

	private static RedisUtils redisUtils;
	private static WechatService wechatService;
	
	
	/**
	 * 获取公众号配置信息
	 * @param uid
	 * @return
	 */
	public static WechatEntity getWechat(String authorizerAppid) {
		String key = "mp_wechat_" + authorizerAppid;
		Object result = redisUtils.getObject(key);
		if (result != null) {
			return (WechatEntity)result;
		}else{
			WechatEntity wechat = wechatService.getWechatEntity(authorizerAppid);
			if(wechat != null && wechat.getId() != null && wechat.getId() > 0){
				redisUtils.setObject(key, wechat);	
			}
			return wechat;
		}
	}
	
	/**
	 * 推送component_verify_ticket协议
	 * @param encrypt
	 */
	public static void setComponentVerifyTicket(String componentVerifyTicket) {
		String key = "component_verify_ticket";
		redisUtils.setObject(key, componentVerifyTicket);	
	}
	
	/**
	 * 获取推送ticket
	 * @return
	 */
	public static String getComponentVerifyTicket() {
		String key = "component_verify_ticket";
		Object result = redisUtils.getObject(key);
		if (result != null) {
			return (String)result;
		}else{
			return "";
		}
	}
    
	
	/**
	 * 获取第三方平台component_access_token
	 * @return
	 */
	public static String getComponentAccessToken() {
		String key = "component_access_token";
		Object result = redisUtils.getObject(key);
		if (result != null) {
			return (String)result;
		}else{
			String componentAccessToken = MpUtils.api_component_token(getComponentVerifyTicket());
			if(StringUtils.isNotEmpty(componentAccessToken)){
				redisUtils.setObject(key, componentAccessToken, 1*60*110);	//1小时50分钟
			}
			return componentAccessToken;
		}
	}
	
	/**
	 * 3、获取预授权码pre_auth_code
	 * @return
	 */
	public static String getPreAuthCode() {
		String key = "pre_auth_code";
		Object result = redisUtils.getObject(key);
		if (result != null) {
			return (String)result;
		}else{
			String preAuthCode = MpUtils.api_create_preauthcode(getComponentAccessToken());
			if(StringUtils.isNotEmpty(preAuthCode)){
				redisUtils.setObject(key, preAuthCode, 1*60*9);	//九分钟
			}
			return preAuthCode;
		}
	}
	
	/**
	 * 获取（刷新）授权公众号或小程序的接口调用凭据（令牌）
	 * @return
	 */
	/*public static String getAuthorizerToken(Long uid) {
		WechatEntity wechat = MpCacheUtils.getWechat(uid);
		String key = "authorizer_token_"+uid;
		Object result = redisUtils.getObject(key);
		if (result != null) {
			return (String)result;
		}else{
			JSONObject r = MpUtils.api_authorizer_token(wechat.getAuthorizerAccessToken(), wechat.getAuthorizationAppid(), wechat.getAuthorizerRefreshToken());
			if(r.containsKey("")){
				redisUtils.setObject(key, preAuthCode, 1*60*110);	//1小时50分钟
			}
			return preAuthCode;
		}
	}*/
	
	/**
	 * 获取授权方令牌
	 * @param appid
	 * @return
	 */
	public static String getAuthorizerAccessToken(String appid) {
		String key = "authorizer_access_token_"+appid;
		Object result = redisUtils.getObject(key);
		if (result != null) {
			return (String)result;
		}else{
			WechatEntity wechat = getWechat(appid);
			JSONObject r = MpUtils.api_authorizer_token(getComponentAccessToken(), wechat.getAuthorizationAppid(), wechat.getAuthorizerRefreshToken());
			if(r.containsKey("authorizer_access_token")){
				wechat.setAuthorizerAccessToken(r.getString("authorizer_access_token"));
				setAuthorizerAccessToken(appid, r.getString("authorizer_access_token"));
			}
			return wechat.getAuthorizerAccessToken();
		}
	}
	
	
	/**
	 * 设置授权方令牌
	 */
	public static void setAuthorizerAccessToken(String appid,String authorizerAccessToken) {
		String key = "authorizer_access_token_"+appid;
		redisUtils.setObject(key, authorizerAccessToken, 1*60*110);	//1小时50分钟
	}
	
	
	
	 /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        return redisUtils.hasKey(key);
    }
    /**
     * 删除缓存
     * @param key 可以传一个值 或多个
     */
	public static void del(String... key) {
		redisUtils.del(key);
	}
	

	


	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		redisUtils = (RedisUtils) applicationContext.getBean("redisUtils");
		wechatService = (WechatService) applicationContext.getBean("wechatService");
	}
}
